package com.woyou.fragment.order;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.jing.biandang.R;
import com.woyou.activity.HomeActivity;
import com.woyou.adapter.OrderDetailsAdapter;
import com.woyou.bean.BoxFee;
import com.woyou.bean.DeliverFee;
import com.woyou.bean.FmInfo;
import com.woyou.bean.Remark;
import com.woyou.bean.WYList;
import com.woyou.bean.rpc.QueryOrderDetailsReq;
import com.woyou.bean.rpc.QueryOrderDetailsRes;
import com.woyou.bean.rpc.Result;
import com.woyou.bean.rpc.SendOrderReq;
import com.woyou.bean.rpc.SendOrderRes;
import com.woyou.component.AutoScrollTextview;
import com.woyou.component.SuperUI;
import com.woyou.event.EventSendOrder;
import com.woyou.fragment.SuperFragment;
import com.woyou.model.rpc.OrderModel;
import com.woyou.utils.FormatTools;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.PrintUtil;
import com.woyou.utils.ThreadPoolManager;
import com.woyou.utils.TypeJudgeTools;

import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.greenrobot.event.EventBus;

public class OrderDetailsFragment extends SuperFragment implements OnClickListener {
	private HomeActivity homeActivity;
	private View layout_details;
	private ListView layout_details_lv;
	private OrderDetailsAdapter orderDetailsAdapter;
	private RelativeLayout layout_details_before;
	private RelativeLayout layout_details_print;
	private RelativeLayout layout_details_next;
	private TextView layout_details_up;
	private TextView layout_details_down;
	private ImageView layout_details_left;
	private ImageView layout_details_right;
	// 动态变化的样式类型
	private LinearLayout layout_details_bg;
	private TextView layout_details_num;
	private TextView layout_details_time;
	private TextView layout_details_status;
	private RelativeLayout layout_details_send;

	private ImageView layout_details_close;
	private AutoScrollTextview layout_details_addrs;
	private TextView layout_details_name;
	private TextView layout_details_sex;
	private TextView layout_details_phone;
	private TextView layout_details_sum;
	// 订单详情
	private int orderPosition = -1;
	private List<Object> goodsList = new ArrayList<Object>();
	private QueryOrderDetailsRes queryOrderDetailsRes;
	private WYList<HashMap<String, String>> wyList;
	private OrderModel orderModel;
	// 订单详情
	private Result<QueryOrderDetailsRes> result;

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (hidden) {
			layout_details_addrs.stopScroll();
		} else {
			initData();
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		layout_details = inflater.inflate(R.layout.layout_order_details, container, false);
		homeActivity = (HomeActivity) getActivity();
		orderModel = OrderModel.getInstance(homeActivity);
		return layout_details;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		// 初始化页面
		initView();
		initData();
	}

	/**
	 * 显示订单详情
	 * 
	 * @param queryOrderDetailsRes
	 */
	public void showOrderDetails(final QueryOrderDetailsRes queryOrderDetailsRes) {
		homeActivity.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				/**
				 * 判断是否有上一页和下一页按钮，如果没有文字和背景置灰色
				 */
				if ((orderPosition - 1) < 0) {
					layout_details_up.setVisibility(View.GONE);
					layout_details_left.setVisibility(View.GONE);
					layout_details_before.setBackgroundResource(R.raw.icon_orderdetails_before_d);
				} else {
					layout_details_up.setVisibility(View.VISIBLE);
					layout_details_left.setVisibility(View.VISIBLE);
					layout_details_before.setBackgroundResource(R.drawable.shape_orderdetails_before);
				}
				if ((orderPosition + 1) > (wyList.size() - 1)) {
					layout_details_down.setVisibility(View.GONE);
					layout_details_right.setVisibility(View.GONE);
					layout_details_next.setBackgroundResource(R.raw.icon_orderdetails_next_d);
				} else {
					layout_details_down.setVisibility(View.VISIBLE);
					layout_details_right.setVisibility(View.VISIBLE);
					layout_details_next.setBackgroundResource(R.drawable.shape_orderdetails_next);
				}

				/**
				 * 是否显示送出按钮
				 */
				if (queryOrderDetailsRes.getOpStatus().equals("已确认")) {
					layout_details_send.setVisibility(View.VISIBLE);
				} else {
					layout_details_send.setVisibility(View.GONE);
				}
				layout_details_num.setText(queryOrderDetailsRes.getShortNo());
				// 下单时间
				long orderTime = Long.valueOf(queryOrderDetailsRes.getOpTime());
				// 判断是预约单还是及时单
				int type = queryOrderDetailsRes.getIsReserve();
				if (type == 1) {
					String rt = FormatTools.convertTimeToZH(homeActivity, queryOrderDetailsRes.getOrderTime() * 1000);
					// 及时单待送出的样式
					if (queryOrderDetailsRes.getOpStatus().equals("已确认")) {
						layout_details_bg.setBackgroundResource(R.raw.orders_bg_red);
						layout_details_num.setTextColor(0xffff8585);
						layout_details_time.setText("尽快	" + rt);
						layout_details_time.setBackgroundColor(0x00000000);
						layout_details_time.setTextColor(0xff000000);
						layout_details_status.setTextColor(0xffdc6b6b);
						String ftime = FormatTools.convertTimeToHtml(homeActivity, orderTime * 1000);
						layout_details_status.setText(Html.fromHtml(queryOrderDetailsRes.getOpStatus() + "," + ftime));
					} else if (queryOrderDetailsRes.getOpStatus().equals("已送出")) {
						// 及时单已送出的样式
						layout_details_bg.setBackgroundResource(R.raw.orders_bg_blue);
						layout_details_num.setTextColor(0xff56c8ff);
						layout_details_time.setText("尽快	" + rt);
						layout_details_time.setBackgroundColor(0x00000000);
						layout_details_time.setTextColor(0xff000000);
						layout_details_status.setTextColor(0xff56c8ff);
						layout_details_status.setText(queryOrderDetailsRes.getOpStatus());
					} else if (queryOrderDetailsRes.getOpStatus().equals("已拒绝")) {
						layout_details_bg.setBackgroundResource(R.raw.orders_bg_purple);
						layout_details_num.setTextColor(0xffc595da);
						layout_details_time.setText("尽快	" + rt);
						layout_details_time.setBackgroundColor(0x00000000);
						layout_details_time.setTextColor(0xff54ad54);
						layout_details_status.setTextColor(0xffc595da);
						layout_details_status.setText(queryOrderDetailsRes.getOpStatus());
					} else {
						// 无效订单
						layout_details_bg.setBackgroundResource(R.raw.orders_bg_purple);
						layout_details_num.setTextColor(0xffc595da);
						layout_details_time.setText("尽快送达	" + rt);
						layout_details_time.setBackgroundColor(0x00000000);
						layout_details_time.setTextColor(0xff54ad54);
						layout_details_status.setTextColor(0xffc595da);
						layout_details_status.setText(queryOrderDetailsRes.getOpStatus());
					}
				} else {
					String ot = FormatTools.convertTime(queryOrderDetailsRes.getReserveTime() * 1000,
							"yyyy-MM-dd HH:mm");
					// 预约单待送出的样式
					if (queryOrderDetailsRes.getOpStatus().equals("已确认")) {
						// 比较预约日期与当前日期的大小
						Date nowDate = new Date();
						if (queryOrderDetailsRes.getOrderTime() * 1000 > nowDate.getTime()) {
							// 预约单待送出未超时
							layout_details_bg.setBackgroundResource(R.raw.orders_bg_green);
							layout_details_num.setTextColor(0xff60d960);
							layout_details_time.setText("预约	" + ot);
							layout_details_time.setBackgroundColor(0xff9eff9e);
							layout_details_time.setTextColor(0xff009600);
							layout_details_status.setTextColor(0xffe8a3a3);
							layout_details_status.setText(queryOrderDetailsRes.getOpStatus());
						} else {
							// 预约单待送出超时
							layout_details_bg.setBackgroundResource(R.raw.orders_bg_red);
							layout_details_num.setTextColor(0xffff6e6e);
							layout_details_time.setText("预约	" + ot);
							layout_details_time.setBackgroundColor(0xff9eff9e);
							layout_details_time.setTextColor(0xff63cf63);
							layout_details_status.setTextColor(0xffe8a3a3);
							layout_details_status.setText(queryOrderDetailsRes.getOpStatus());
						}
					} else if (queryOrderDetailsRes.getOpStatus().equals("已送出")) {
						// 预约单已送出的样式
						layout_details_bg.setBackgroundResource(R.raw.orders_bg_blue);
						layout_details_num.setTextColor(0xff56c8ff);
						layout_details_time.setText("预约	" + ot);
						layout_details_time.setBackgroundColor(0xff9eff9e);
						layout_details_time.setTextColor(0xff54ad54);
						layout_details_status.setTextColor(0xff98dcff);
						layout_details_status.setText(queryOrderDetailsRes.getOpStatus());
					} else {
						// 无效订单
						layout_details_bg.setBackgroundResource(R.raw.orders_bg_purple);
						layout_details_num.setTextColor(0xffc595da);
						layout_details_time.setText("预约	" + ot);
						layout_details_time.setBackgroundColor(0xff9eff9e);
						layout_details_time.setTextColor(0xff54ad54);
						layout_details_status.setTextColor(0xffc595da);
						layout_details_status.setText(queryOrderDetailsRes.getOpStatus());
					}
				}

				layout_details_addrs.setText(queryOrderDetailsRes.getAddr());
				if (layout_details_addrs.dip2px(homeActivity, 440) <= (int) layout_details_addrs.init()) {
					layout_details_addrs.startScroll();
				}
				layout_details_name.setText(queryOrderDetailsRes.getContact());
				// 判断该用户性别
				if (queryOrderDetailsRes.getSex() == 1) {
					layout_details_sex.setText("小姐");
				} else if (queryOrderDetailsRes.getSex() == 2) {
					layout_details_sex.setText("先生");
				} else {
					layout_details_sex.setText("");
				}

				layout_details_phone.setText(queryOrderDetailsRes.getPhone());
				if (queryOrderDetailsRes.getOpStatus().equals("已拒绝") || queryOrderDetailsRes.getOpStatus().equals("已取消")
						|| queryOrderDetailsRes.getOpStatus().equals("未应答")
						|| queryOrderDetailsRes.getOpStatus().equals("接通后未应答")) {
					layout_details_phone.setVisibility(View.INVISIBLE);
				} else {
					layout_details_phone.setVisibility(View.VISIBLE);
				}

				if (queryOrderDetailsRes.getIsPay() == 0) {
					layout_details_sum.setText(Html.fromHtml(
							"<small>¥</small>" + FormatTools.String2Money(queryOrderDetailsRes.getSumFee() + "")
									+ "<small> ( 已支付 ) </small>"));
				} else {
					layout_details_sum.setText(Html.fromHtml(
							"<small>¥</small>" + FormatTools.String2Money(queryOrderDetailsRes.getSumFee() + "")));
				}

				// 重置列表
				goodsList.clear();
				// 添加商品
				if (queryOrderDetailsRes.getGoodsList() != null && queryOrderDetailsRes.getGoodsList().size() > 0) {
					goodsList.addAll(queryOrderDetailsRes.getGoodsList());
				}
				// 外送费
				if (queryOrderDetailsRes.getDeliverFee() > 0) {
					DeliverFee deliverFee = new DeliverFee();
					deliverFee.setPrice(queryOrderDetailsRes.getDeliverFee());
					goodsList.add(deliverFee);
				}
				// 餐盒费
				if (queryOrderDetailsRes.getBoxFee() > 0) {
					BoxFee boxFee = new BoxFee();
					boxFee.setType(queryOrderDetailsRes.getBoxType());
					boxFee.setNum(queryOrderDetailsRes.getBoxNum());
					boxFee.setPrice(queryOrderDetailsRes.getBoxFee());
					goodsList.add(boxFee);
				}
				// 添加赠品
				if (queryOrderDetailsRes.getGiftList() != null && queryOrderDetailsRes.getGiftList().size() > 0) {
					goodsList.addAll(queryOrderDetailsRes.getGiftList());
				}
				// 添加优惠券
				if (queryOrderDetailsRes.getCouponList() != null && queryOrderDetailsRes.getCouponList().size() > 0) {
					goodsList.addAll(queryOrderDetailsRes.getCouponList());
				}
				// 添加备注
				if (!TypeJudgeTools.isNull(queryOrderDetailsRes.getRemark())) {
					Remark remark = new Remark();
					remark.setRemark(queryOrderDetailsRes.getRemark());
					goodsList.add(remark);
				}
				if (goodsList != null) {
					orderDetailsAdapter = new OrderDetailsAdapter(mContext, goodsList);
					layout_details_lv.setAdapter(orderDetailsAdapter);
				} else {
					SuperUI.openToast(homeActivity, "无法获取订单商品信息！");
				}
			}
		});

	}

	/**
	 * 初始化页面
	 */
	public void initView() {
		layout_details_bg = (LinearLayout) layout_details.findViewById(R.id.layout_details_bg);
		layout_details_num = (TextView) layout_details.findViewById(R.id.layout_details_num);
		layout_details_time = (TextView) layout_details.findViewById(R.id.layout_details_time);
		layout_details_status = (TextView) layout_details.findViewById(R.id.layout_details_status);
		layout_details_close = (ImageView) layout_details.findViewById(R.id.layout_details_close);
		layout_details_addrs = (AutoScrollTextview) layout_details.findViewById(R.id.layout_details_addrs);
		layout_details_name = (TextView) layout_details.findViewById(R.id.layout_details_name);
		layout_details_sex = (TextView) layout_details.findViewById(R.id.layout_details_sex);
		layout_details_phone = (TextView) layout_details.findViewById(R.id.layout_details_phone);
		layout_details_sum = (TextView) layout_details.findViewById(R.id.layout_details_sum);

		layout_details_lv = (ListView) layout_details.findViewById(R.id.layout_details_lv);
		layout_details_before = (RelativeLayout) layout_details.findViewById(R.id.layout_details_before);
		layout_details_print = (RelativeLayout) layout_details.findViewById(R.id.layout_details_print);
		layout_details_send = (RelativeLayout) layout_details.findViewById(R.id.layout_details_send);
		layout_details_next = (RelativeLayout) layout_details.findViewById(R.id.layout_details_next);
		layout_details_up = (TextView) layout_details.findViewById(R.id.layout_details_up);
		layout_details_left = (ImageView) layout_details.findViewById(R.id.layout_details_left);
		layout_details_down = (TextView) layout_details.findViewById(R.id.layout_details_down);
		layout_details_right = (ImageView) layout_details.findViewById(R.id.layout_details_right);

		layout_details_close.setOnClickListener(this);
		layout_details_before.setOnClickListener(this);
		layout_details_print.setOnClickListener(this);
		layout_details_send.setOnClickListener(this);
		layout_details_next.setOnClickListener(this);
	}
	/**
	 * 加载上一单或者下一单数据数据判断
	 * @param isUpPage上一页：true; 下一页：false;
	 */
	private void loadData(final boolean isUpPage) {
		// 获取订单详情
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					// 点击上一页
					if (isUpPage) {
						if ((orderPosition - 1) < 0) {
							homeActivity.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									SuperUI.openToast(homeActivity, "没有上一单了");
								}
							});
						} else {
							orderPosition = orderPosition - 1;
							QueryOrderDetailsReq queryOrderDetailsReq = new QueryOrderDetailsReq();
							queryOrderDetailsReq.setoId(wyList.get(orderPosition).get("No"));
							queryOrderDetailsReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
							queryOrderDetailsReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
							result = orderModel.v2_3queryOrderDetails(queryOrderDetailsReq);
							if (result != null && result.getCode() == 1) {
								queryOrderDetailsRes = result.getData();
								showOrderDetails(queryOrderDetailsRes);
							} else if (result != null && result.getCode() == -3) {
								homeActivity.homeController.exitLogin();
							}
						}
					} else {
						// 点击下一页
						if ((orderPosition + 1) > (wyList.size() - 1)) {
							homeActivity.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									SuperUI.openToast(homeActivity, "没有下一单了");
								}
							});
						} else {
							orderPosition = orderPosition + 1;
							QueryOrderDetailsReq queryOrderDetailsReq = new QueryOrderDetailsReq();
							queryOrderDetailsReq.setoId(wyList.get(orderPosition).get("No"));
							queryOrderDetailsReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
							queryOrderDetailsReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
							result = orderModel.v2_3queryOrderDetails(queryOrderDetailsReq);
							if (result != null && result.getCode() == 1) {
								queryOrderDetailsRes = result.getData();
								showOrderDetails(queryOrderDetailsRes);
							} else if (result != null && result.getCode() == -3) {
								homeActivity.homeController.exitLogin();
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		wyList = (WYList<HashMap<String, String>>) aCache.getAsObject("OrderList");
		orderPosition = Integer.valueOf(aCache.getAsString("Position"));
		queryOrderDetailsRes = (QueryOrderDetailsRes) aCache.getAsObject("orderDetail");
		homeActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (queryOrderDetailsRes != null) {
					showOrderDetails(queryOrderDetailsRes);
				} else {
					SuperUI.openToast(homeActivity, "无法获取订单详情");
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_details_close:
			returnOrderFragment();
			break;
		case R.id.layout_details_before:
			loadData(true);
			break;
		case R.id.layout_details_print:
			try {
				/**
				 * 开启线程，去打印订单
				 */
				ThreadPoolManager.getInstance().executeTask(new Runnable() {
					@Override
					public void run() {
						try {
							if (queryOrderDetailsRes != null) {
								final boolean isOk = PrintUtil.printOrder(homeActivity, queryOrderDetailsRes);
								homeActivity.runOnUiThread(new Runnable() {
									@Override
									public void run() {
										if (!isOk) {
											SuperUI.openToast(homeActivity, "请检查您的打印机");
										}
									}
								});
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
				SuperUI.openToast(homeActivity, "请检查您的打印机");
			}
			break;
		case R.id.layout_details_send:
			sendOrder();
			break;
		case R.id.layout_details_next:
			loadData(false);
			break;
		}
	}

	/**
	 * 送出订单
	 */
	public void sendOrder() {
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					SendOrderReq sendOrderReq = new SendOrderReq();
					sendOrderReq.setoId(queryOrderDetailsRes.getoId());
					sendOrderReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
					sendOrderReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
					Result<SendOrderRes> result = orderModel.sendOrder(sendOrderReq);
					if (result != null && result.getCode() == 1) {
						EventBus.getDefault().post(new EventSendOrder(result.getData()));
						returnOrderFragment();
					} else if (result != null && result.getCode() == -3) {
						homeActivity.homeController.exitLogin();
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 返回订单列表
	 */
	public void returnOrderFragment() {
		homeActivity.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				homeActivity.openFM(new FmInfo(OrderFragment.class, null, false));
			}
		});
	}
}
